﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using Runda.CMS.Bll;
using System.Data;

namespace Runda.CMS.Portal.Mobile
{
    public partial class MaintainInfo : BasePage
    {
        public Guid RegisterID
        {
            get 
            {
                if (Request.QueryString["RegisterID"] != null)
                {
                    return new Guid(Request.QueryString["RegisterID"]);
                }
                else return Guid.Empty;
            }
        }

        public Guid MaintainID
        {
            get
            {
                if (hiddenMaintainID.Text == string.Empty) return Guid.Empty;
                else return new Guid(hiddenMaintainID.Text);
            }
            set
            {
                hiddenMaintainID.Text = value.ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (RegisterID == Guid.Empty) return;

                ddlGuaranteeInfo.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.GuaranteeType)));
                SystemBll bll = new SystemBll();
                WsmMaintainBillEntity entity = null;
                entity = bll.Get<WsmMaintainBillEntity>(" and RegisterID = '" + RegisterID + "'");

                if (entity != null)
                {
                    MaintainID = entity.MaintainID;
                }

                WsmTaskRegisterEntity registerEntity = new SystemBll().Get<WsmTaskRegisterEntity>(RegisterID);
                if (registerEntity != null)
                {
                    CtrtCustomerEntity cusEntity = new SystemBll().Get<CtrtCustomerEntity>(registerEntity.CustomerID);
                    if(cusEntity != null)
                        txtCustomName.Text = cusEntity.CustomerName;

                    WsmInstrumentInfoEntity InstrumentEntity = new SystemBll().Get<WsmInstrumentInfoEntity>(registerEntity.InstrumentID);
                    if (InstrumentEntity != null)
                    {
                        txtInstrumentName.Text = InstrumentEntity.instrumentName;
                        txtInstrumentBelongTo.Text = InstrumentEntity.Vendor;
                    }
                    txtInstrumentSerialNum.Text = registerEntity.InstrumentSerialNum;

                    List<WsmCustomerContactorEntity> contactors = new SystemBll().GetAll<WsmCustomerContactorEntity>(" and CustomerID = '" + registerEntity.CustomerID.ToString() + "'");
                    foreach (WsmCustomerContactorEntity contactor in contactors)
                    {
                        UsersContacter.Items.Add(new ListItem(contactor.ContactorName, contactor.ContactorID.ToString()));
                    }
                }

                if (entity == null)
                {
                    txtEmpName.Text = base.CurrentUserEntity.UserName;
                    txtReceiveDate.Value = System.DateTime.Now.ToShortDateString();
                    txtBeginDate.Value = System.DateTime.Now.ToShortDateString();
                    txtEndDate.Value = System.DateTime.Now.ToShortDateString();
                    txtEndTime.Value = System.DateTime.Now.ToShortTimeString();
                    return;
                }

                txtBillNo.Text = entity.PaperInvoicesNo;
                txtEmpName.Text = new SystemBll().Get<SysUserEntity>(base.CurrentUserID).UserName;
                ddlGuaranteeInfo.SelectedValue = entity.GuaranteeInfo;
                ddlServiceLevel.SelectedValue = entity.ServiceLevel;
                txtServicePurpose.Text = entity.ServicePurpose;
                if (entity.ReceiveDate != DateTime.MinValue)
                {
                    txtReceiveDate.Value = entity.ReceiveDate.ToString("yyyy-MM-dd");
                    txtReceiveTime.Value = entity.ReceiveDate.ToString("HH:mm");
                }

                txtRecommendContent.Text = entity.RecommendContent;
                if (entity.BeginDate != DateTime.MinValue)
                {
                    txtBeginDate.Value = entity.BeginDate.ToString("yyyy-MM-dd");
                    txtBeginTime.Value = entity.BeginDate.ToString("HH:mm");
                }
                txtOnWayTime.Value = entity.OnWayTime.ToString();
                txtInstrumentSerialNum.Text = entity.InstrumentSerialNum;

                //if (txtReachFare.Value.HasValue)
                //    entity.ReachFare = Convert.ToDecimal(txtReachFare.Value.Value);

                //if (txtLeaveFare.Value.HasValue)
                //    entity.LeaveFare = Convert.ToDecimal(txtLeaveFare.Value.Value);

                //if (txtAccommodationFee.Value.HasValue)
                //    entity.AccommodationFee = Convert.ToDecimal(txtAccommodationFee.Value.Value);

                if (entity.EndTime != DateTime.MinValue)
                {
                    txtEndDate.Value = entity.EndTime.ToString("yyyy-MM-dd");
                    txtEndTime.Value = entity.EndTime.ToString("HH:mm");
                }

                //entity.UsersContacter = UsersContacter.SelectedValue;
                UsersContacter.SelectedValue = entity.UsersContacter;
                txtWorkContent.Text = entity.WorkContent;
                //entity.FaultCode = txtFaultCode.Text;
                //entity.FaultComponents = ddlFaultComponents.SelectedValue.ToString();


                this.ddltServicedStatus.SelectedValue = entity.ServicedStatus;

                List<WsmInstrumentRecordEntity> recordList = new SystemBll().GetAll<WsmInstrumentRecordEntity>(" and SerialNum = '" + entity.InstrumentSerialNum + "' and CustomerID='" + registerEntity.CustomerID.ToString() + "'");
                if (recordList != null && recordList.Count > 0)
                {                   
                    ReadNumType.SelectedValue = recordList[0].ReadNumType.ToString();
                }
                List<WsmInstrumentRecordEntity> list = new SystemBll().GetAll<WsmInstrumentRecordEntity>(" and MaintainID='" + MaintainID.ToString() + "'");
                if (list != null && list.Count > 0)
                {
                    ReadNumType.SelectedValue = list[0].ReadNumType.ToString();
                    ReadNum.Text = list[0].TotalNum.ToString();
                    ReadNumAverageDaily.Text = list[0].DailyNum.ToString();                  
                }
                DataTable dtnearlyRecord = new WsmInstrumentRecordBll().GetInstrumentRecordByConfirmParms(entity.InstrumentSerialNum, registerEntity.InstrumentID, registerEntity.CustomerID);
                if (dtnearlyRecord != null && dtnearlyRecord.Rows.Count > 0)
                {
                    hiddenLastRecordNum.Text = dtnearlyRecord.Rows[0]["TotalNum"].ToString();
                    hiddenLastRecordDate.Text = dtnearlyRecord.Rows[0]["RecordDate"].ToString();
                    lastDailyNum.Text = dtnearlyRecord.Rows[0]["DailyNum"].ToString();
                }
                else
                {
                    hiddenLastRecordNum.Text = "0";
                    hiddenLastRecordDate.Text = DateTime.Now.ToString();
                    lastDailyNum.Text = "0";
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            WsmMaintainBillEntity entity = new WsmMaintainBillEntity();
            SystemBll bll = new SystemBll();

            List<WsmMaintainBillEntity> list = new SystemBll().GetAll<WsmMaintainBillEntity>(" and RegisterID='" + RegisterID.ToString() + "'");

            if (list != null && list.Count > 0)
            {
                entity = list[0];
                MaintainID = entity.MaintainID;
            }
            

            WsmTaskRegisterEntity taskEntity = new SystemBll().Get<WsmTaskRegisterEntity>(RegisterID);
            
            //if (MaintainID != Guid.Empty)
            //{
            //    entity = bll.Get<WsmMaintainBillEntity>(" and MaintainID = '" + MaintainID + "'");
            //}
            if (MaintainID != Guid.Empty)
            {
                //entity = bll.Get<WsmMaintainBillEntity>(MaintainID);
            }
            else
            {
                entity = new WsmMaintainBillEntity();
                entity.PaperInvoicesNo = new CommonBll().getCode("PaperInvoicesNo");
                entity.CreatedBy = CurrentUserID;
                entity.CreatedOn = DateTime.Now;
                entity.Deleted = 0;
                entity.RegisterID = RegisterID;
                MaintainID = entity.MaintainID;
                entity.Maintainer = base.CurrentUserID;
            }

            //entity.PaperInvoicesNo = txtBillNo.Text;
            entity.GuaranteeInfo = ddlGuaranteeInfo.SelectedValue.ToString();

            entity.ServiceLevel = ddlServiceLevel.SelectedValue;
            entity.ServicePurpose = txtServicePurpose.Text.Trim();
            if (txtReceiveDate.Value.Trim() != "")
            {
                if (txtReceiveTime.Value.Trim() != "")
                {
                    entity.ReceiveDate = Convert.ToDateTime(txtReceiveDate.Value.Trim() + " " + txtReceiveTime.Value.Trim());
                }
                else
                {
                    entity.ReceiveDate = Convert.ToDateTime(txtReceiveDate.Value.Trim());
                }
            }
            entity.RecommendContent = txtRecommendContent.Text.Trim();

            if (txtBeginDate.Value.Trim() != "")
            {
                if (txtBeginTime.Value.Trim() != "")
                {
                    entity.BeginDate = Convert.ToDateTime(txtBeginDate.Value.Trim() + " " + txtBeginTime.Value.Trim());
                }
                else
                {
                    entity.BeginDate = Convert.ToDateTime(txtBeginDate.Value.Trim());
                }
            }
 
            entity.OnWayTime = System.Convert.ToInt32(txtOnWayTime.Value.Trim());
            entity.InstrumentSerialNum = txtInstrumentSerialNum.Text.Trim();

            //if (txtReachFare.Value.HasValue)
            //    entity.ReachFare = Convert.ToDecimal(txtReachFare.Value.Value);

            //if (txtLeaveFare.Value.HasValue)
            //    entity.LeaveFare = Convert.ToDecimal(txtLeaveFare.Value.Value);

            //if (txtAccommodationFee.Value.HasValue)
            //    entity.AccommodationFee = Convert.ToDecimal(txtAccommodationFee.Value.Value);

            if (txtEndDate.Value.Trim() != "")
            {
                if (txtEndDate.Value.Trim() != "")
                {
                    entity.EndTime = Convert.ToDateTime(txtEndDate.Value.Trim() + " " + txtEndTime.Value.Trim());
                }
                else
                {
                    entity.EndTime = Convert.ToDateTime(txtEndDate.Value.Trim());
                }
            }

            entity.UsersContacter = UsersContacter.SelectedValue;
            entity.WorkContent = txtWorkContent.Text;
            //entity.FaultCode = txtFaultCode.Text;
            //entity.FaultComponents = ddlFaultComponents.SelectedValue.ToString();
         

            entity.ServicedStatus = this.ddltServicedStatus.SelectedValue.ToString();
            //entity.Maintainer = new Guid(employeeGUID.Value);
            //entity.CheckAt = System.DateTime.Now;
            //entity.CheckerID = base.CurrentUserID;
            //entity.CheckerName = base.CurrentUserEntity.UserName.ToString();
            bll.InsertOrUpdate(entity);

            if (ReadNumAverageDaily.Text != "")
            {
                WsmInstrumentRecordEntity recordEntity = new WsmInstrumentRecordEntity();
                recordEntity.RecordID = Guid.NewGuid();
                recordEntity.Recorder = CurrentUserID;
                recordEntity.RecordDate = DateTime.Now;
                recordEntity.InstrumentID = taskEntity.InstrumentID;
                recordEntity.CreatedBy = CurrentUserID;
                recordEntity.CreatedOn = DateTime.Now;
                recordEntity.ReadNumType = System.Convert.ToInt32(ReadNumType.SelectedValue);
                recordEntity.Deleted = false;
                recordEntity.MaintainID = MaintainID;
                recordEntity.CustomerID = taskEntity.CustomerID;
                if (entity.InstrumentSerialNum == null || entity.InstrumentSerialNum == "")
                    recordEntity.SerialNum = DateTime.Now.ToString();
                else
                    recordEntity.SerialNum = entity.InstrumentSerialNum;
                if (ReadNumType.SelectedValue == "1")
                {
                    if (hiddenLastRecordNum.Text == "" || hiddenLastRecordNum.Text == null) { hiddenLastRecordNum.Text = "0"; }
                    if (System.Convert.ToDecimal(ReadNum.Text) < System.Convert.ToDecimal(hiddenLastRecordNum.Text))
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "saveerror", "alert('计数总数不能小于上次总数');", true);
                    }
                    recordEntity.TotalNum = System.Convert.ToDecimal(ReadNum.Text);
                    if (hiddenLastRecordNum.Text != "0")
                    {
                        decimal lastTotal = System.Convert.ToDecimal(hiddenLastRecordNum.Text);
                        DateTime lastRecordDate = System.Convert.ToDateTime(hiddenLastRecordDate.Text);
                        int interval = recordEntity.RecordDate.Date.Subtract(lastRecordDate.Date).Days;
                        decimal intevalRecord = System.Convert.ToDecimal(ReadNum.Text) - lastTotal;
                        decimal averRecord = intevalRecord / interval;
                        recordEntity.DailyNum = averRecord;
                    }
                    else
                    {
                        recordEntity.DailyNum = System.Convert.ToDecimal(ReadNum.Text);
                    }
                }
                if (ReadNumType.SelectedValue == "2")
                {
                    recordEntity.DailyNum = System.Convert.ToDecimal(ReadNumAverageDaily.Text);
                }
                bll.Insert(recordEntity);
            }


            Response.Redirect("Maintainlist.aspx");
            //ClientScript.RegisterStartupScript(this.GetType(), "SaveSuccess", "window.location='Maintainlist.aspx';", true);
        }
    }
}
